package logic

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"order/model"
	"order/order"
	"order/utils"

	"order/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RefundLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRefundLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefundLogic {
	return &RefundLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RefundLogic) Refund(in *order.RefundRequest) (*order.RefundResponse, error) {
	if exist := model.FindOrderGoodsIsPayById(in.Id); !exist {
		return nil, status.Error(codes.InvalidArgument, "你未购买过该商品")
	}

	result := model.Db.Model(&model.OrderGoods{}).Where("id = ?", in.Id).Updates(model.OrderGoods{Status: 3, LogisticsStatus: 4})
	if result.Error != nil && result.RowsAffected == 0 {
		return nil, status.Error(codes.InvalidArgument, "refund fail")
	}

	orderGoodsModel, err := model.FindOrderGoodsById(in.Id)
	if err != nil {
		return nil, err
	}
	//if orderGoodsModel == nil {
	//	return nil, status.Error(codes.InvalidArgument, "你未下单该商品")
	//}

	return &order.RefundResponse{
		OrderGoodsData: utils.OrderGoodsModelToProto(*orderGoodsModel),
	}, err
}
